<template>
  <view class="list-container">
    <!-- 顶部导航 -->
    <view class="top-nav">
      <view class="nav-back" @click="goBack">
        <text class="icon">&#xf060;</text>
      </view>
      <text class="nav-title">我的作品</text>
      <view class="nav-filter" @click="showFilterModal = true">
        <text class="icon">&#xf0b0;</text>
      </view>
    </view>

    <!-- 筛选标签 -->
    <view class="filter-tabs">
      <view
        v-for="tab in filterTabs"
        :key="tab.value"
        class="tab-item"
        :class="{ active: currentFilter === tab.value }"
        @click="changeFilter(tab.value)"
      >
        <text class="tab-text">{{ tab.label }}</text>
        <text class="tab-count">{{ tab.count }}</text>
      </view>
    </view>

    <!-- 作品列表 -->
    <scroll-view
      scroll-y
      class="list-scroll"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      :refresher-threshold="100"
      :lower-threshold="50"
    >
      <view class="list-content">
        <view
          v-for="work in workList"
          :key="work.jobId"
          class="work-item"
          @click="viewDetail(work)"
        >
          <view class="work-cover">
            <image
              v-if="work.status === 'SUCCESS' && work.videoUrl"
              :src="
                work.videoUrl + '?x-oss-process=video/snapshot,t_1000,m_fast'
              "
              mode="aspectFill"
              class="cover-image"
            />
            <view v-else class="cover-placeholder">
              <text
                class="icon"
                :class="{ spinning: work.status === 'ON_QUEUE' }"
              >
                {{ work.status === "ON_QUEUE" ? "&#xf110;" : "&#xf03d;" }}
              </text>
            </view>
            <!-- 状态标签 -->
            <view class="status-badge" :class="work.status.toLowerCase()">
              <text class="icon">
                {{
                  work.status === "SUCCESS"
                    ? "&#xf00c;"
                    : work.status === "ON_QUEUE"
                    ? "&#xf110;"
                    : "&#xf00d;"
                }}
              </text>
              <text>{{ formatStatus(work.status) }}</text>
            </view>
            <!-- 播放按钮 -->
            <view v-if="work.status === 'SUCCESS'" class="play-btn">
              <text class="icon">&#xf04b;</text>
            </view>
          </view>

          <view class="work-info">
            <text class="work-prompt">{{ work.prompt }}</text>
            <view class="work-meta">
              <view class="meta-item">
                <text class="icon">&#xf017;</text>
                <text>{{ formatTime(work._add_time) }}</text>
              </view>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="work-actions">
            <view
              v-if="work.status === 'SUCCESS'"
              class="action-btn save"
              @click.stop="quickSave(work)"
            >
              <text class="icon">&#xf0c7;</text>
            </view>
            <view
              v-if="work.status === 'SUCCESS'"
              class="action-btn download"
              @click.stop="quickDownload(work)"
            >
              <text class="icon">&#xf019;</text>
            </view>
            <view
              v-if="work.status === 'ON_QUEUE'"
              class="action-btn refresh"
              @click.stop="refreshTask(work)"
            >
              <text class="icon">&#xf021;</text>
            </view>
            <view class="action-btn delete" @click.stop="confirmDelete(work)">
              <text class="icon">&#xf1f8;</text>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="hasMore" class="load-more">
          <text class="icon spinning">&#xf110;</text>
          <text>加载中...</text>
        </view>
        <view v-else-if="workList.length > 0" class="no-more">
          <text>没有更多了</text>
        </view>

        <!-- 空状态 -->
        <view v-if="workList.length === 0 && !loading" class="empty-state">
          <text class="empty-icon">📹</text>
          <text class="empty-text">还没有作品</text>
          <text class="empty-desc">快去创作你的第一个视频吧</text>
          <button class="create-btn" @click="goToCreate">
            <text class="icon">&#xf067;</text>
            <text>开始创作</text>
          </button>
        </view>
      </view>
    </scroll-view>

    <!-- 筛选弹窗 -->
    <view
      v-if="showFilterModal"
      class="filter-modal"
      @click="showFilterModal = false"
    >
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">筛选</text>
          <text class="modal-close" @click="showFilterModal = false"
            >&#xf00d;</text
          >
        </view>
        <view class="filter-options">
          <view class="option-group">
            <text class="group-title">状态</text>
            <view class="option-list">
              <view
                v-for="option in statusOptions"
                :key="option.value"
                class="option-item"
                :class="{ active: selectedStatus === option.value }"
                @click="selectedStatus = option.value"
              >
                <text>{{ option.label }}</text>
                <text class="icon">&#xf00c;</text>
              </view>
            </view>
          </view>
          <view class="option-group">
            <text class="group-title">排序</text>
            <view class="option-list">
              <view
                v-for="option in sortOptions"
                :key="option.value"
                class="option-item"
                :class="{ active: selectedSort === option.value }"
                @click="selectedSort = option.value"
              >
                <text>{{ option.label }}</text>
                <text class="icon">&#xf00c;</text>
              </view>
            </view>
          </view>
        </view>
        <view class="modal-actions">
          <button class="modal-btn reset" @click="resetFilter">重置</button>
          <button class="modal-btn confirm" @click="applyFilter">确定</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      workList: [],
      currentFilter: "",
      pageIndex: 1,
      pageSize: 10,
      hasMore: true,
      loading: false,
      refreshing: false,
      showFilterModal: false,
      selectedStatus: "",
      selectedSort: "time_desc",
      filterTabs: [
        { label: "全部", value: "", count: 0 },
        { label: "生成中", value: "ON_QUEUE", count: 0 },
        { label: "已完成", value: "SUCCESS", count: 0 },
        { label: "失败", value: "FAILED", count: 0 },
      ],
      statusOptions: [
        { label: "全部", value: "" },
        { label: "生成中", value: "ON_QUEUE" },
        { label: "已完成", value: "SUCCESS" },
        { label: "失败", value: "FAILED" },
      ],
      sortOptions: [
        { label: "最新创建", value: "time_desc" },
        { label: "最早创建", value: "time_asc" },
      ],
    };
  },
  onLoad() {
    this.loadList();
    this.loadCounts();
  },
  methods: {
    // 加载列表
    async loadList(refresh = false) {
      if (this.loading && !refresh) return;

      this.loading = true;
      if (refresh) {
        this.pageIndex = 1;
        this.workList = [];
      }

      try {
        const res = await vk.callFunction({
          url: "client/sora/kh/getTaskList",
          data: {
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            status: this.currentFilter || undefined,
          },
        });

        if (res.code === 0) {
          if (refresh) {
            this.workList = res.rows || [];
          } else {
            this.workList = this.workList.concat(res.rows || []);
          }
          this.hasMore = res.hasMore || false;
        }
      } catch (error) {
        console.error("加载列表失败:", error);
      } finally {
        this.loading = false;
        // 不在这里重置 refreshing，让 onRefresh 方法统一处理
      }
    },

    // 加载统计数量
    async loadCounts() {
      for (let tab of this.filterTabs) {
        try {
          const res = await vk.callFunction({
            url: "client/sora/kh/getTaskList",
            data: {
              pageIndex: 1,
              pageSize: 1,
              status: tab.value || undefined,
            },
          });
          if (res.code === 0) {
            tab.count = res.total || 0;
          }
        } catch (error) {
          console.error("加载统计失败:", error);
        }
      }
    },

    // 切换筛选
    changeFilter(value) {
      this.currentFilter = value;
      this.loadList(true);
    },

    // 下拉刷新
    async onRefresh() {
      console.log("下拉刷新触发");
      if (this.refreshing) return; // 防止重复触发

      this.refreshing = true;
      this.pageIndex = 1;
      this.workList = [];

      try {
        // 加载列表数据
        const res = await vk.callFunction({
          url: "client/sora/kh/getTaskList",
          data: {
            pageIndex: 1,
            pageSize: this.pageSize,
            status: this.currentFilter || undefined,
          },
        });

        if (res.code === 0) {
          this.workList = res.rows || [];
          this.hasMore = res.hasMore || false;
        }

        // 加载统计数据
        this.loadCounts();
      } catch (error) {
        console.error("刷新失败:", error);
      } finally {
        // 立即重置状态
        this.$nextTick(() => {
          this.refreshing = false;
          console.log("刷新完成");
        });
      }
    },

    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.pageIndex++;
        this.loadList();
      }
    },

    // 刷新任务
    // 快速保存到相册
    quickSave(work) {
      if (!work || !work.videoUrl) {
        uni.showToast({
          title: "视频地址不存在",
          icon: "none",
        });
        return;
      }

      uni.showLoading({ title: "保存中..." });

      uni.downloadFile({
        url: work.videoUrl,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveVideoToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.hideLoading();
                uni.showToast({
                  title: "已保存到相册",
                  icon: "success",
                  duration: 2000,
                });
              },
              fail: (err) => {
                console.error("保存到相册失败:", err);
                uni.hideLoading();

                if (err.errMsg && err.errMsg.indexOf("auth") !== -1) {
                  uni.showModal({
                    title: "需要相册权限",
                    content: "请在设置中允许访问相册",
                    confirmText: "去设置",
                    success: (modalRes) => {
                      if (modalRes.confirm) {
                        uni.openSetting();
                      }
                    },
                  });
                } else {
                  uni.showToast({
                    title: "保存失败，请重试",
                    icon: "none",
                  });
                }
              },
            });
          } else {
            uni.hideLoading();
            uni.showToast({
              title: "下载失败",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          console.error("下载失败:", err);
          uni.hideLoading();
          uni.showToast({
            title: "下载失败，请检查网络",
            icon: "none",
          });
        },
      });
    },

    // 快速下载
    quickDownload(work) {
      if (!work || !work.videoUrl) {
        uni.showToast({
          title: "视频地址不存在",
          icon: "none",
        });
        return;
      }

      // #ifdef H5
      const a = document.createElement("a");
      a.href = work.videoUrl;
      a.download = `sora_video_${work.jobId}.mp4`;
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      uni.showToast({
        title: "开始下载",
        icon: "success",
      });
      // #endif

      // #ifdef APP-PLUS || MP-WEIXIN
      // APP 和小程序都使用保存到相册的方式
      this.quickSave(work);
      // #endif
    },

    async refreshTask(work) {
      try {
        const res = await vk.callFunction({
          url: "client/sora/kh/pollTask",
          data: {
            jobId: work.jobId,
            forceUpdate: true,
          },
        });

        if (res.code === 0) {
          // 更新本地数据
          const index = this.workList.findIndex(
            (item) => item.jobId === work.jobId
          );
          if (index !== -1) {
            this.workList.splice(index, 1, res.data);
          }

          if (res.status === "SUCCESS") {
            uni.showToast({
              title: "视频生成成功",
              icon: "success",
            });
          } else if (res.status === "FAILED") {
            uni.showToast({
              title: "视频生成失败",
              icon: "none",
            });
          }
        }
      } catch (error) {
        console.error("刷新失败:", error);
      }
    },

    // 确认删除
    confirmDelete(work) {
      uni.showModal({
        title: "确认删除",
        content: "删除后无法恢复，确定要删除这个任务吗？",
        success: (res) => {
          if (res.confirm) {
            this.deleteTask(work);
          }
        },
      });
    },

    // 删除任务
    async deleteTask(work) {
      try {
        const res = await vk.callFunction({
          url: "client/sora/kh/deleteTask",
          data: {
            jobId: work.jobId,
          },
        });

        if (res.code === 0) {
          uni.showToast({
            title: "删除成功",
            icon: "success",
          });
          // 从列表中移除
          const index = this.workList.findIndex(
            (item) => item.jobId === work.jobId
          );
          if (index !== -1) {
            this.workList.splice(index, 1);
          }
          this.loadCounts();
        }
      } catch (error) {
        console.error("删除失败:", error);
        uni.showToast({
          title: "删除失败",
          icon: "none",
        });
      }
    },

    // 应用筛选
    applyFilter() {
      this.currentFilter = this.selectedStatus;
      this.showFilterModal = false;
      this.loadList(true);
    },

    // 重置筛选
    resetFilter() {
      this.selectedStatus = "";
      this.selectedSort = "time_desc";
    },

    // 查看详情
    viewDetail(work) {
      uni.navigateTo({
        url: `/pages/sora/detail?jobId=${work.jobId}`,
      });
    },

    // 返回
    goBack() {
      uni.navigateBack();
    },

    // 去创作
    goToCreate() {
      uni.navigateBack();
    },

    // 格式化状态
    formatStatus(status) {
      const map = {
        ON_QUEUE: "生成中",
        SUCCESS: "已完成",
        FAILED: "失败",
      };
      return map[status] || status;
    },

    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp);
      const Y = date.getFullYear();
      const M = (date.getMonth() + 1).toString().padStart(2, "0");
      const D = date.getDate().toString().padStart(2, "0");
      const h = date.getHours().toString().padStart(2, "0");
      const m = date.getMinutes().toString().padStart(2, "0");
      return `${M}-${D} ${h}:${m}`;
    },
  },
};
</script>

<style scoped>
page {
  background: #0a0a0a;
}

.list-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #0a0a0a 0%, #1a1a2e 100%);
}

/* 顶部导航 */
.top-nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 40rpx;
  padding-top: calc(30rpx + constant(safe-area-inset-top));
  padding-top: calc(30rpx + env(safe-area-inset-top));
  background: rgba(255, 255, 255, 0.03);
  backdrop-filter: blur(20px);
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.05);
  z-index: 999;
}

.nav-back,
.nav-filter {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  background: rgba(139, 92, 246, 0.1);
  border: 1rpx solid rgba(139, 92, 246, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon {
  font-family: FontAwesome;
  font-size: 32rpx;
  color: #8b5cf6;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
}

/* 筛选标签 */
.filter-tabs {
  position: fixed;
  top: calc(130rpx + constant(safe-area-inset-top));
  top: calc(130rpx + env(safe-area-inset-top));
  left: 0;
  right: 0;
  width: 100%;
  display: flex;
  padding: 30rpx 40rpx;
  gap: 20rpx;
  overflow-x: auto;
  background: linear-gradient(180deg, #0a0a0a 0%, rgba(26, 26, 46, 0.95) 100%);
  backdrop-filter: blur(20px);
  z-index: 998;
}

.tab-item {
  flex-shrink: 0;
  padding: 20rpx 40rpx;
  background: rgba(255, 255, 255, 0.03);
  border-radius: 50rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.05);
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.tab-item.active {
  background: rgba(139, 92, 246, 0.2);
  border-color: rgba(139, 92, 246, 0.5);
}

.tab-text {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.6);
}

.tab-item.active .tab-text {
  color: #8b5cf6;
  font-weight: bold;
}

.tab-count {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.4);
  padding: 4rpx 12rpx;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 20rpx;
}

.tab-item.active .tab-count {
  background: rgba(139, 92, 246, 0.3);
  color: #8b5cf6;
}

/* 列表内容 */
.list-scroll {
  position: fixed;
  top: calc(240rpx + constant(safe-area-inset-top));
  top: calc(240rpx + env(safe-area-inset-top));
  left: 0;
  right: 0;
  bottom: 0;
  height: auto;
}

.list-content {
  padding: 20rpx 40rpx 40rpx;
}

.work-item {
  display: flex;
  background: rgba(255, 255, 255, 0.03);
  border-radius: 30rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.05);
  position: relative;
}

.work-cover {
  position: relative;
  width: 240rpx;
  height: 240rpx;
  border-radius: 20rpx;
  overflow: hidden;
  flex-shrink: 0;
  background: rgba(0, 0, 0, 0.3);
}

.cover-image {
  width: 100%;
  height: 100%;
}

.cover-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.cover-placeholder .icon {
  font-size: 80rpx;
}

.status-badge {
  position: absolute;
  top: 16rpx;
  left: 16rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 20rpx;
  color: #fff;
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  gap: 6rpx;
}

.status-badge .icon {
  font-size: 20rpx;
}

.status-badge.on_queue {
  background: rgba(251, 191, 36, 0.8);
}

.status-badge.success {
  background: rgba(34, 197, 94, 0.8);
}

.status-badge.failed {
  background: rgba(239, 68, 68, 0.8);
}

.play-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: rgba(139, 92, 246, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 30rpx rgba(139, 92, 246, 0.4);
}

.play-btn .icon {
  font-size: 40rpx;
  color: #fff;
  margin-left: 6rpx;
}

.work-info {
  flex: 1;
  padding: 10rpx 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.work-prompt {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 20rpx;
}

.work-meta {
  display: flex;
  gap: 30rpx;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.5);
}

.meta-item .icon {
  font-size: 24rpx;
}

.work-actions {
  position: absolute;
  right: 20rpx;
  bottom: 20rpx;
  display: flex;
  gap: 20rpx;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.05);
  border: 1rpx solid rgba(255, 255, 255, 0.1);
}

.action-btn .icon {
  font-size: 28rpx;
}

.action-btn.save .icon {
  color: #8b5cf6;
}

.action-btn.download .icon {
  color: #10b981;
}

.action-btn.refresh .icon {
  color: #3b82f6;
}

.action-btn.delete .icon {
  color: #ef4444;
}

/* 加载更多 */
.load-more,
.no-more {
  text-align: center;
  padding: 40rpx;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.load-more .icon {
  font-size: 32rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 60rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 36rpx;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 20rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.4);
  margin-bottom: 60rpx;
}

.create-btn {
  padding: 24rpx 60rpx;
  background: linear-gradient(135deg, #8b5cf6 0%, #ec4899 100%);
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  font-size: 28rpx;
  font-weight: bold;
  color: #fff;
  border: none;
}

.create-btn .icon {
  font-size: 28rpx;
  color: #fff;
}

/* 筛选弹窗 */
.filter-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: flex-end;
  z-index: 999;
}

.modal-content {
  width: 100%;
  max-height: 70vh;
  background: #1a1a2e;
  border-radius: 40rpx 40rpx 0 0;
  padding: 40rpx;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
}

.modal-close {
  font-family: FontAwesome;
  font-size: 40rpx;
  color: rgba(255, 255, 255, 0.6);
}

.filter-options {
  max-height: 50vh;
  overflow-y: auto;
}

.option-group {
  margin-bottom: 40rpx;
}

.group-title {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 20rpx;
}

.option-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.option-item {
  padding: 20rpx 40rpx;
  background: rgba(255, 255, 255, 0.03);
  border-radius: 50rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.05);
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.6);
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.option-item .icon {
  font-size: 24rpx;
  opacity: 0;
}

.option-item.active {
  background: rgba(139, 92, 246, 0.2);
  border-color: rgba(139, 92, 246, 0.5);
  color: #8b5cf6;
}

.option-item.active .icon {
  opacity: 1;
  color: #8b5cf6;
}

.modal-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 40rpx;
}

.modal-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 50rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
}

.modal-btn.reset {
  background: rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.6);
}

.modal-btn.confirm {
  background: linear-gradient(135deg, #8b5cf6 0%, #ec4899 100%);
  color: #fff;
}

/* 动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.spinning {
  animation: spin 1s linear infinite;
}
</style>
